//
//  XFMapManager.m
//  WorkManager
//
//  Created by ukongm on 17/2/18.
//  Copyright © 2017年 ukongm. All rights reserved.
//

#import "XFMapManager.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相关所有的头文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地图功能所有的头文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
#import <CoreLocation/CoreLocation.h>

@interface XFMapManager()<CLLocationManagerDelegate,BMKMapViewDelegate,BMKLocationServiceDelegate>

#pragma mark - 系统地位
/** 解析 */
@property(nonatomic,strong)CLGeocoder* geocoder;
/** 定位 */
@property(nonatomic,strong)CLLocationManager* location;

#pragma mark - 百度定位
/** 地图控件 */
@property(nonatomic,strong)BMKMapView* mapView;
/** 百度定位 */
@property(nonatomic,strong)BMKLocationService* locationBMK;
/** 大头针 */
@property(nonatomic,strong)BMKPointAnnotation* annotation;
/** 大头针 */
@property(nonatomic,strong)BMKPinAnnotationView* annotationView;

@end

@implementation XFMapManager
{
    void (^_complate)(NSString *);
}

#pragma mark - 百度地图
+ (void)initialManager{
    // 要使用百度地图，请先启动
    BMKMapManager* mapManager = [[BMKMapManager alloc]init];
    // 如果要关注网络及授权验证事件，请设定generalDelegate参数
    BOOL ret = [mapManager start:@"zjAL1iPQ62MBVe0LIR0cqd0EsumGBo4x" generalDelegate:nil];
    
    if (ret) {
        
    }
}

- (BMKPinAnnotationView *)annotationView{
    
    if (_annotationView == nil) {
        _annotationView = [[BMKPinAnnotationView alloc] init];
    }
    return _annotationView;
}

- (BMKPointAnnotation*)annotation{
    if (_annotation == nil) {
        _annotation = [[BMKPointAnnotation alloc] init];
    }
    return _annotation;
}

- (BMKLocationService *)locationBMK{
    
    if (_locationBMK == nil) {
        _locationBMK = [[BMKLocationService alloc] init];
        _locationBMK.delegate = self;
    }
    return _locationBMK;
}

- (BMKMapView *)mapView{
    
    if (_mapView == nil) {
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        _mapView.mapType = BMKMapTypeStandard;
        _mapView.userTrackingMode = BMKUserTrackingModeFollow;
        _mapView.delegate = self;
        _mapView.gesturesEnabled = NO;
        [_mapView setZoomEnabled:YES];
        [_mapView setZoomLevel:18];//级别，3-19
    }
    
    return _mapView;
}

- (UIView*)addMapToTarget:(UIView *)targetView frame:(CGRect)frame{
    self.mapView.frame = frame;
    [targetView addSubview:self.mapView];
    return self.mapView;
}

- (void)mapViewDidFinishLoading:(BMKMapView *)mapView{
    //开始定位
    [self.locationBMK startUserLocationService];
}

//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    self.mapView.showsUserLocation = YES;
    [self.mapView updateLocationData:userLocation];
    [self.mapView setCenterCoordinate:userLocation.location.coordinate];
//    self.annotation.title = userLocation.title;
//    self.annotation.subtitle = userLocation.subtitle;
//    [self.annotation setCoordinate:userLocation.location.coordinate];
//    [self.mapView addAnnotation:self.annotation];
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        
        if (self.annotationView) {
//            [self.annotationView removeFromSuperview];
//            [self.mapView removeAnnotation:self.annotation];
        }
        
        self.annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        self.annotationView.pinColor = BMKPinAnnotationColorRed;
        self.annotationView.animatesDrop = NO;// 设置该标注点动画显示
        return self.annotationView;
    }
    return nil;
}

- (void)viewWillDisappear{
    [self.mapView viewWillDisappear];
    [self.locationBMK stopUserLocationService];
}

- (void)viewWillAppear{
    [self.mapView viewWillAppear];
    
    [self.locationBMK startUserLocationService];
}

#pragma mark 系统
- (CLLocationManager *)location{
    
    if (_location == nil) {
        _location = [[CLLocationManager alloc] init];
        _location.delegate = self;
        //设置定位精度
        _location.desiredAccuracy=kCLLocationAccuracyBestForNavigation;
        //定位频率,每隔多少米定位一次
        CLLocationDistance distance=10.0;//十米定位一次
        _location.distanceFilter=distance;
    }
    return _location;
}
- (CLGeocoder *)geocoder{
    
    if (_geocoder == nil) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

+ (instancetype)singletonManager{
    static dispatch_once_t onceToken;
    static XFMapManager* manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [XFMapManager new];
    });
    
    return manager;
}

- (void)getPlaceName:(void (^)(NSString *))complate{
    _complate = complate;
    
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [self.location requestWhenInUseAuthorization];
    }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
        
        if (complate) {
            complate(nil);
        }
        
    }else{
        //开启定位
        [self.location startUpdatingLocation];
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
    //如果不需要实时定位，使用完即使关闭定位服务
    [self.location stopUpdatingLocation];

    [self getAddressByLatitude:coordinate.latitude longitude:coordinate.longitude];
    
}

#pragma mark 根据坐标取得地名
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placemark=[placemarks firstObject];
        if (placemark.locality == nil) {
            return ;
        }

        NSString* reuslt = [NSString stringWithFormat:@"%@%@%@",placemark.locality,placemark.subLocality,placemark.name];

        if (_complate) {
            _complate(reuslt);
        }
        
    }];
}


@end
